package com.example.hrsystem.workflow;

import android.app.Application;
import android.content.Context;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.hrsystem.workflow.engine.WorkflowEngine;
import com.example.hrsystem.workflow.model.ProcessDefinition;
import com.example.hrsystem.workflow.model.ProcessInstance;
import com.example.hrsystem.workflow.model.WorkflowTask;
import com.example.hrsystem.workflow.repository.WorkflowRepository;
import com.example.hrsystem.workflow.repository.WorkflowRepositoryImpl;

import java.util.List;

/**
 * 工作流ViewModel
 * 负责处理工作流相关的业务逻辑和数据管理
 */
public class WorkflowViewModel extends AndroidViewModel {
    private MutableLiveData<List<WorkflowTask>> userTasks = new MutableLiveData<>();
    private MutableLiveData<List<ProcessDefinition>> allProcessDefinitions = new MutableLiveData<>();
    private MutableLiveData<ProcessDefinition> processDefinition = new MutableLiveData<>();
    private MutableLiveData<Boolean> loading = new MutableLiveData<>();
    private MutableLiveData<String> error = new MutableLiveData<>();

    private WorkflowRepository workflowRepository;
    private WorkflowEngine workflowEngine;

    public WorkflowViewModel(Application application) {
        super(application);
        // 初始化仓库和引擎，传递Context参数
        workflowRepository = new WorkflowRepositoryImpl(application);
        workflowEngine = new WorkflowEngine(workflowRepository);
    }

    public LiveData<List<WorkflowTask>> getUserTasks() {
        return userTasks;
    }

    public LiveData<List<ProcessDefinition>> getAllProcessDefinitions() {
        return allProcessDefinitions;
    }

    public LiveData<ProcessDefinition> getProcessDefinitionById(int id) {
        loading.setValue(true);
        try {
            ProcessDefinition definition = workflowRepository.getProcessDefinitionById(id);
            processDefinition.setValue(definition);
            error.setValue(null);
        } catch (Exception e) {
            error.setValue("获取流程定义失败: " + e.getMessage());
        } finally {
            loading.setValue(false);
        }
        return processDefinition;
    }

    public LiveData<Boolean> getLoading() {
        return loading;
    }

    public LiveData<String> getError() {
        return error;
    }

    /**
     * 加载用户的工作流任务列表
     *
     * @param userId 用户ID
     */
    public void loadUserTasks(int userId) {
        loading.setValue(true);
        try {
            List<WorkflowTask> tasks = workflowEngine.getUserTasks(userId);
            userTasks.setValue(tasks);
            error.setValue(null);
        } catch (Exception e) {
            error.setValue("加载任务失败: " + e.getMessage());
        } finally {
            loading.setValue(false);
        }
    }

    /**
     * 加载所有流程定义
     */
    public void loadAllProcessDefinitions() {
        loading.setValue(true);
        try {
            List<ProcessDefinition> processDefinitions = workflowRepository.getAllProcessDefinitions();
            allProcessDefinitions.setValue(processDefinitions);
            error.setValue(null);
        } catch (Exception e) {
            error.setValue("加载流程定义失败: " + e.getMessage());
        } finally {
            loading.setValue(false);
        }
    }

    /**
     * 保存流程定义
     *
     * @param processDefinition 流程定义
     */
    public void saveProcessDefinition(ProcessDefinition processDefinition) {
        loading.setValue(true);
        try {
            workflowRepository.saveProcessDefinition(processDefinition);
            // 重新加载列表
            loadAllProcessDefinitions();
            error.setValue(null);
        } catch (Exception e) {
            error.setValue("保存流程定义失败: " + e.getMessage());
        } finally {
            loading.setValue(false);
        }
    }

    /**
     * 更新流程定义
     *
     * @param processDefinition 流程定义
     */
    public void updateProcessDefinition(ProcessDefinition processDefinition) {
        loading.setValue(true);
        try {
            workflowRepository.updateProcessDefinition(processDefinition);
            // 重新加载列表
            loadAllProcessDefinitions();
            error.setValue(null);
        } catch (Exception e) {
            error.setValue("更新流程定义失败: " + e.getMessage());
        } finally {
            loading.setValue(false);
        }
    }

    /**
     * 删除流程定义
     *
     * @param id 流程定义ID
     */
    public void deleteProcessDefinition(int id) {
        loading.setValue(true);
        try {
            workflowRepository.deleteProcessDefinition(id);
            // 重新加载列表
            loadAllProcessDefinitions();
            error.setValue(null);
        } catch (Exception e) {
            error.setValue("删除流程定义失败: " + e.getMessage());
        } finally {
            loading.setValue(false);
        }
    }

    /**
     * 根据ID获取流程实例
     *
     * @param instanceId 流程实例ID
     * @return 流程实例对象
     */
    public ProcessInstance getProcessInstanceById(int instanceId) {
        try {
            return workflowRepository.getProcessInstanceById(instanceId);
        } catch (Exception e) {
            error.setValue("获取流程实例失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 获取流程实例的任务历史记录
     *
     * @param processInstanceId 流程实例ID
     * @return 任务列表
     */
    public List<WorkflowTask> getTasksByProcessInstance(int processInstanceId) {
        try {
            return workflowRepository.getTasksByProcessInstance(processInstanceId);
        } catch (Exception e) {
            error.setValue("获取任务历史记录失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 处理任务
     *
     * @param taskId 任务ID
     * @param assigneeId 处理人ID
     * @param action 处理动作
     */
    public void handleTask(int taskId, int assigneeId, String action) {
        loading.setValue(true);
        try {
            boolean success = workflowEngine.handleTask(taskId, assigneeId, action);
            if (success) {
                // 重新加载任务列表
                loadUserTasks(assigneeId);
                error.setValue(null);
            } else {
                error.setValue("任务处理失败");
            }
        } catch (Exception e) {
            error.setValue(e.getMessage());
        } finally {
            loading.setValue(false);
        }
    }
}